package com.klun.tjy.tjyes.client;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetAddress;

@Component
public class ESFactory implements FactoryBean<TransportClient> {

    private static Logger log = LoggerFactory.getLogger(ESFactory.class);

    @Value("${elasticsearch.cluster-name}")
    private String CLUSTER_NAME;

    @Value("${elasticsearch.cluster-nodes}")
    private String CLUSTER_NODES;

    @Override
    public TransportClient getObject() throws Exception {
        return initClient();
    }

    private TransportClient initClient() {
        //创建访问es服务器的客户端
        TransportClient client = null;
        try {
            System.setProperty("es.set.netty.runtime.available.processors", "false");
            //指定ES集群
            Settings settings = Settings.builder().put("cluster.name", CLUSTER_NAME).build();
            log.info("ES ready ---------> " + CLUSTER_NAME + "---" + CLUSTER_NODES);
            String[] nodes = CLUSTER_NODES.split(",");
            client = new PreBuiltTransportClient(settings);
            for (String node : nodes) {
                String[] node_arg = StringUtils.split(StringUtils.trimToEmpty(node), ":");
                client.addTransportAddress(
                        new TransportAddress(InetAddress.getByName(StringUtils.trimToEmpty(node_arg[0])),
                                Integer.parseInt(StringUtils.trimToEmpty(node_arg[1])))
                );
            }
            log.info("ES start ---------> " + CLUSTER_NAME + "---" + CLUSTER_NODES);
        } catch (Exception e) {
            log.error("error", e);
        }
        return client;
    }

    @Override
    public Class<?> getObjectType() {
        return TransportClient.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
